package com.sgb.capital.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.capital.R;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.base.BasePopWindow;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.InvoiceFlowActivityBinding;
import com.sgb.capital.model.Bean;
import com.sgb.capital.model.InvoiceFeesBean;
import com.sgb.capital.utils.AdapterOnItemClick;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.SelectPop;
import com.sgb.capital.view.widget.xrecyclerview.ZXRecyclerView;
import com.sgb.capital.viewmodel.InvoiceFlowModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

/**
 * 开票流水列表
 * @author cyj
 */
public class InvoiceFlowActivity extends BaseActivity {

    private InvoiceFlowActivityBinding mBinding;
    private InvoiceFlowModel mModel;
    private SelectPop mSelectPop;
    private InvoiceFeesBean invoiceFeesBean = new InvoiceFeesBean();

    /** 跳转 开票流水列表 页面 */
    public static void start(Context context) {
        Intent intent = new Intent(context, InvoiceFlowActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        // viewModel绑定
        mBinding = DataBindingUtil.setContentView(this, R.layout.invoice_flow_activity);
        mModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(InvoiceFlowModel.class);
        mBinding.setInvoiceFlowModel(mModel);
        mBinding.rvList.setLayoutManager(new LinearLayoutManager(Utils.getContext()));
        mBinding.rvList.setAdapter(mModel.invoiceFlowAdapter);
        // 初始化查询时间视图
        mSelectPop = new SelectPop(InvoiceFlowActivity.this, 0);
        mSelectPop.setBgView(mBinding.grayLayout);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            // 查询费用开票列表
            invoiceFeesBean.page = 1;
            mModel.getInvoiceFlowList(invoiceFeesBean);
        }, 300);
    }

    @Override
    public void initData() {
        super.initData();
        // 查询费用开票列表
        invoiceFeesBean.page = 1;
        mModel.getInvoiceFlowList(invoiceFeesBean);

        List<Bean> mTimeBeans = new ArrayList<>();
        mTimeBeans.add(new Bean("全部"));
        mTimeBeans.add(new Bean("今日"));
        mTimeBeans.add(new Bean("最近一周"));
        mTimeBeans.add(new Bean("最近一月"));
        mTimeBeans.add(new Bean("最近一年"));
        mSelectPop.setData(mTimeBeans);
    }

    @Override
    public void initObserve() {
        mModel.invoiceFlowListLiveData.observe(this, data -> {
            mBinding.rvList.refreshComplete();
            if (data == null) return;
            if (invoiceFeesBean.page == 1) {
                mBinding.rvList.setVisibility(data.size() != 0 ? View.VISIBLE : View.GONE);
                mBinding.errorView.setVisibility(data.size() != 0 ? View.GONE : View.VISIBLE);
                mBinding.rvList.setLoadingMoreEnabled(true);
                mBinding.rvList.refreshComplete();
                if (data.size() < 20) {
                    mBinding.rvList.setNoMore(true);
                }
            } else {
                if (data.size() != 0) {
                    mBinding.rvList.loadMoreComplete();
                } else {
                    mBinding.rvList.setNoMore(true);
                }
            }
        });
    }

    @Override
    public void initListener() {
        super.initListener();
        mBinding.ivBack.setOnClickListener(v -> finish());
        mModel.invoiceFlowAdapter.setOnItemClick(new AdapterOnItemClick<InvoiceFeesBean>() {

            @Override
            public void onItemClick(InvoiceFeesBean invoiceFeesBean, int position) {
                // 设置item对应的单选按钮选中状态（此处与IOS同一点击item则默认选中事件触发）
                invoiceFeesBean.isChecked.set(!invoiceFeesBean.isChecked.get());
                // 列表item选中实时计算金额并更新UI
                mModel.itemClickForAddMoney(invoiceFeesBean);
                mModel.hasCheckedAll.set(false);
            }
        });
        mBinding.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                invoiceFeesBean.page = 1;
                invoiceFeesBean.searchValue = mBinding.etSearch.getText().toString().trim();
                mModel.getInvoiceFlowList(invoiceFeesBean);
            }
            return false;
        });
        mBinding.rvList.setLoadingListener(new ZXRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                invoiceFeesBean.page = 1;
                mModel.getInvoiceFlowList(invoiceFeesBean);
            }

            @Override
            public void onLoadMore() {
                invoiceFeesBean.page++;
                mModel.getInvoiceFlowList(invoiceFeesBean);
            }
        });
        mSelectPop.setOnDismissListener(() -> {
            mBinding.img.setRotation(0);
            if (mSelectPop.mIsClick) {
                mBinding.tvName.setText(mSelectPop.mPos1 == 0 ? "全部" : mSelectPop.mBean.name);
                mBinding.tvName.setTextColor(Utils.getColor(mSelectPop.mPos1 != 0 ? R.color.color_EF4033 : R.color.color_666666));
                mBinding.img.setImageResource(mSelectPop.mPos1 != 0 ? R.mipmap.down : R.mipmap.ic_down_arrow_n);
                String mTime = "";
                if (mSelectPop.mPos1 != 0) {
                    mTime = mSelectPop.mBean.name.contains("今日") ? Utils.getStartAndEndTime(0, 0, "今日")
                            : mSelectPop.mBean.name.contains("最近一周") ? Utils.getStartAndEndTime(1, 0, "最近一周")
                            : mSelectPop.mBean.name.contains("最近一月") ? Utils.getStartAndEndTime(2, 0, "最近一月")
                            : Utils.getStartAndEndTime(3, 0, "最近一年");
                    invoiceFeesBean.startTime = mTime.split("-")[0];
                    invoiceFeesBean.endTime = mTime.split("-")[1];
                } else {
                    invoiceFeesBean.startTime = null;
                    invoiceFeesBean.endTime = null;
                }
                mSelectPop.mIsClick = false;
                invoiceFeesBean.page = 1;
                mModel.getInvoiceFlowList(invoiceFeesBean);
            } else {
                mBinding.tvName.setTextColor(Utils.getColor( R.color.color_666666));
            }
        });
        mBinding.llView.setOnClickListener(v -> {
            mBinding.img.setRotation(180);
            mSelectPop.showPopwindow(mBinding.view, 0, 0);
            mBinding.tvName.setTextColor(Utils.getColor( R.color.color_333333));
        });
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void confirmInvoiceJumpAsiaRecord(ZMessageEvent event) {
        if(Constants.EVENT_CONFIRM_INVOICE_JUMP_ASIA_RECORD == event.code) {
            finish();
        }
    }
}
